#!usr/bin/python
# encoding=utf-8

'''
Created on May 4, 2014

@author: root
'''

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from wm.lib.loglib import log_error,log_info
from wm.db.TransactionManager import TransactionManager

def sendMail(subject,content,mailto):
	'''
	@邮件发送函数
	@逻辑：从osa_email_config获取邮件服务信息，进行邮件发送
	'''
	tran = TransactionManager()
	try:
		sql = "select * from wt_email_config limit 1"
		result = tran.select(sql)
		tran.commitTransaction()
		if not result or result == None:
			log_error('SMTP不能用,原因：数据表email_config为空')
			print 'SMTP不能用,原因：数据表email_config为空'
			return
	except:
		tran.rollbackTransaction()
	finally:
		tran.close()
		
	smtp_server = result[0][6] #host
	smtp_from = result[0][4]   #sendaddress
	smtp_user = result[0][5]   #user
	smtp_pass = result[0][8]   #password
	smtp_port = result[0][9]   #port
	
	msg = MIMEMultipart()
	msg['Subject'] = Header(subject,'utf-8')
	msg['From'] = smtp_from
	msg['To'] = mailto

	part =  MIMEText(content,'plain','utf-8')
	msg.attach(part)

	try:
		smtpServer = smtplib.SMTP(smtp_server,str(smtp_port))		
	except Exception as e:
		log_error('SMTP连接邮件服务器失败,可能原因:'+str(e))
		return False
	try:
		smtpServer.login(smtp_user,smtp_pass)
		smtpServer.sendmail(smtp_from,mailto,msg.as_string())
		print 'send mail to:',mailto
		log_info('send mail to:'+mailto)
	except smtplib.SMTPException as e:
		log_error('SMTP发送邮件失败,可能原因:'+str(e))
		print 'SMTP发送邮件失败,可能原因:',str(e)
	finally:
		smtpServer.quit()
		return True
		
def get_mailto_users(user_list='ALL'):
	'''
	@根据user_list的值来获取需要通知的用户列表
	'''
	tran = TransactionManager()
	try:
		tran.startTransaction()
		userlist = []
		if user_list=='ALL':
			users = tran.select("select username from user where isEnabled=1")
			tran.commitTransaction()
			for user in users:
				userlist.append(user[0])
			return userlist
		else:
			for user in user_list.split(','):
				userlist.append(user)
			return userlist
	except:
		tran.rollbackTransaction()
	finally:
		tran.close()

if __name__ == '__main__':
	#mail_to = ";".join(["pez1420@163.com","luyou2008@qq.com"])
	mail_to = "pez1420@163.com"
	#sendMail("python mail test", "djklsffffffffffffffffffffffffffffffffff",mail_to)
	print get_mailto_users()
	pass
